<?php

namespace application\vote\controller;

use application\admin\controller\base as auth;
use ticky\request;
use application\vote\models\vote_option_model;

class vote extends auth {

    public function index() {
        $search = array('siteid' => $this->siteid);
        $ret = db('vote_subject')->where($search)->order('subjectid desc')->newpage();
        $this->assign('page', $ret['page']);
        $this->assign('items', $ret['items']);
        $this->display('vote_list');
    }

    /**
     * 添加投票
     */
    public function add() {
        load_extend('form.class.php');
        if (request::isPost()) {
            $_POST['optionnumber'] = count($_POST['option']);
            $_POST['template'] = trim($_POST['template']);
            $_POST['addtime'] = time();
            $post_data = trim_script($_POST);
            $subjectid = db('vote_subject')->insert($post_data);
            //添加选项操作
            vote_option_model::add_options($post_data['option'], $subjectid, $this->siteid);
            //生成JS文件
            $this->update_votejs($subjectid);
            showmsg('添加成功', '/vote/vote/index');
        } else {
            $this->assign('postUrl', '/vote/vote/add');
            $this->assign('action', '添加');
            $this->display('vote_manage');
        }
    }

    /**
     * 编辑投票
     */
    public function update() {
        $subjectid = request::get('subjectid', 0);
        load_extend('form.class.php');
        if (request::isPost()) {
            $_POST['template'] = $_POST['template'];
            $_POST['addtime'] = time();
            $post_data = trim_script($_POST);
            vote_option_model::update_options($post_data['option']); //先更新已有 投票选项,再添加新增加投票选项
            if (is_array($_POST['newoption']) && !empty($_POST['newoption'])) {
                vote_option_model::add_options($post_data['newoption'], $subjectid, $this->siteid);
            }
            $_POST['optionnumber'] = count($_POST['option']);
            db('vote_subject')->update($post_data, array('subjectid' => $subjectid));
            //生成JS文件
            $this->update_votejs($subjectid);
            showmsg('修改成功', '/vote/vote/index');
        } else {

            $item = db('vote_subject')->where(['subjectid' => $subjectid])->find();
            $options = vote_option_model::get_options($subjectid);

            $this->assign('postUrl', '/vote/vote/update');
            $this->assign('action', '修改');
            $this->assign('item', $item);
            $this->assign('options', $options);
            $this->display('vote_manage');
        }
    }

    /**
     * 删除投票
     * @param	intval	$sid	投票的ID，递归删除
     */
    public function delete() {
        $subjectid = request::get('subjectid', 0);
        db('vote_subject')->delete(array('subjectid' => $subjectid));
        db('vote_option')->delete(array('subjectid' => $subjectid));
        db('vote_data')->delete(array('subjectid' => $subjectid));
        showmsg('删除成功！', '/vote/vote');
    }

    /**
     * 投票结果统计
     */
    public function statistics() {
        $subjectid = intval($_GET['subjectid']);
        if (!$subjectid) {
            showmsg(L('illegal_operation'));
        }
        //新建一数组用来存新组合数据
        $total = 0;
        $vote_data = array();
        $vote_data['total'] = 0; //所有投票选项总数
        $vote_data['votes'] = 0; //投票人数
        //获取投票结果信息
        $infos = db('vote_data')->where(['subjectid' => $subjectid])->select();
        //循环每个会员的投票记录
        foreach ($infos as $subjectid_arr) {
            extract($subjectid_arr);
            $arr = string2array($data);
            foreach ($arr as $key => $values) {
                $vote_data[$key] += 1;
            }
            $total += array_sum($arr);
            $vote_data['votes'] ++;
        }
        $vote_data['total'] = $total;
        //获取投票选项
        $options = vote_option_model::get_options($subjectid);
        $vote_options = array();
        foreach ($options as $option) {
            if ($vote_data['total'] == 0) {
                $option['per'] = 0;
            } else {
                $option['per'] = intval($vote_data[$option['optionid']] / $vote_data['total'] * 100);
            }
            $option['num'] = $vote_data[$option['optionid']] == '' ? '0' : $vote_data[$option['optionid']];
            $vote_options[] = $option;
        }
        $subject_arr = db('vote_subject')->where(['subjectid' => $subjectid])->find();
        $this->assign('vote_data', $vote_data);
        $this->assign('vote_options', $vote_options);
        $this->assign('vote_subject', $subject_arr);
        $this->assign('vote_user', $infos);
        $this->display('vote_statistics');
    }

    /**
     * 投票会员统计
     */
    public function statistics_userlist() {
        $subjectid = intval($_GET['subjectid']);
        if (!$subjectid) {
            showmsg(L('illegal_operation'));
        }
        $ret = db('vote_data')->where(['subjectid' => $subjectid])->newpage();
        $this->assign('page', $ret['page']);
        $this->assign('vote_user', $ret['items']);
        $this->display('vote_statistics_userlist');
    }

    /**
     * 投票调用代码
     */
    public function public_call() {
        $subjectid = intval($_GET['subjectid']);
        if (!$subjectid)
            showmsg(L('illegal_action'), HTTP_REFERER);
        $item = db('vote_subject')->where(['subjectid' => $subjectid])->find();
        $this->assign('item', $item);
        $this->display('vote_call');
    }

    /**
     * 说明:生成JS投票代码
     * @param $subjectid 投票ID
     */
    private function update_votejs($subjectid) {
        if (!isset($subjectid) || intval($subjectid) < 1)
            return false;
        //解出投票内容
        $info = db('vote_subject')->where(['subjectid' => $subjectid])->find();
        if (!$info) {
            showmsg(L('not_vote'));
        }
        //解出投票选项
        $options = vote_option_model::get_options($subjectid);
        ob_start();
        include template($info['template'], 'home');
        $voteform = ob_get_contents();
        ob_clean();
        @file_put_contents(RUNTIME_PATH . '/cache/vote/vote_' . $subjectid . '.js', $this->format_js($voteform));
    }

    /**
     * 说明:对字符串进行处理
     * @param $string 待处理的字符串
     * @param $isjs 是否生成JS代码
     */
    private function format_js($string, $isjs = 1) {
        $string = addslashes(str_replace(array("\r", "\n"), array('', ''), $string));
        return $isjs ? 'document.write("' . $string . '");' : $string;
    }

}
